package com.lan.schedule;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 一个定时任务
 */

public class AlarmService extends Service {
    String PREFS_NAME = "state";
    String str1[] = new String[36];
    GradientDrawable.Orientation or[] = {GradientDrawable.Orientation.TL_BR, GradientDrawable.Orientation.BR_TL, GradientDrawable.Orientation.BL_TR, GradientDrawable.Orientation.TR_BL, GradientDrawable.Orientation.TOP_BOTTOM, GradientDrawable.Orientation.BOTTOM_TOP, GradientDrawable.Orientation.LEFT_RIGHT, GradientDrawable.Orientation.RIGHT_LEFT};
    String str2[] = new String[26];
     int[][] colorcan = new int[6][3];
    int ifcolor[] = new int[6];
    int grcolor[] = new int[6];

    public int dpToPx(int dps) {
        return Math.round(getResources().getDisplayMetrics().density * dps);
    }
    public void fr() {
        colorcan[3][0] = 0xFFFFFFFF;
        colorcan[5][0] = 0x00FFFFFF;
        colorcan[0][1] = 0xFF000000;
        colorcan[0][2] = 0xFFFF0000;
        for (int i = 0; i < 6; i++) {
            ifcolor[i] = 0;
            grcolor[i] = 5;
        }
        colorcan[5][0] = 0x00FFFFFF;
        colorcan[4][0] = 0xFFFFFFFF;
        colorcan[0][0] = 0xFF000000;
        colorcan[1][0] = 0xFF880000;
        colorcan[2][0] = 0x55ffffff;
        colorcan[3][0] = 0xffeeeeee;
    }

    String mYear;
    String mMonth;
    String mDay;
    String mWay;
    int flag1 = 1;
    int fla = -9;
    int ba = 0xffff0000;
    int sh = 0x55ffffff;
    int fo = 0xff000000;
    int alp = 100;

    public void setc() {
        try {
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
            FileInputStream ff = new FileInputStream(strFilePath + "/th1.txt");
            FileChannel channel = ff.getChannel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));


            fla = Integer.parseInt(bufferedReader.readLine());
            alp = Integer.parseInt(bufferedReader.readLine());
            for (int y = 0; y < 6; y++) {
                ifcolor[y] = Integer.parseInt(bufferedReader.readLine());
                grcolor[y] = Integer.parseInt(bufferedReader.readLine());
                for (int x = 0; x < 3; x++) {
                    colorcan[y][x] = Integer.parseInt(bufferedReader.readLine());
                }
            }

            channel.close();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  System.out.println(fla+","+ba);
    }

    @SuppressLint("WrongConstant")
    private Bitmap getBitmapGradient(int aa) {
        GradientDrawable drawable1 = new GradientDrawable();
        if(aa==1){
            drawable1.setShape(GradientDrawable.RECTANGLE);
            drawable1.setGradientType(GradientDrawable.RECTANGLE);
            drawable1.setCornerRadius(50);
            if (ifcolor[1] == 0)
                drawable1.setColor(colorcan[1][0]);
            else {
                int[] colors = {colorcan[1][1], colorcan[1][2]};
                drawable1.setColors(colors);
                drawable1.setOrientation(or[grcolor[1]]);
            }
        }else{
        if (ifcolor[2] == 0) {
                drawable1.setShape(GradientDrawable.RECTANGLE);
                drawable1.setGradientType(GradientDrawable.RECTANGLE);
                drawable1.setCornerRadius(50);
                drawable1.setStroke(10, colorcan[3][0]);
                drawable1.setColor(colorcan[2][0]);
        } else {
            int[] cs = {colorcan[2][1], colorcan[2][2]};
                drawable1.setShape(GradientDrawable.RECTANGLE);
                drawable1.setGradientType(GradientDrawable.RECTANGLE);
                drawable1.setCornerRadius(50);
                drawable1.setStroke(10, colorcan[3][0]);
                drawable1.setColors(cs);
                drawable1.setOrientation(or[grcolor[2]]);
        }}
        //我这图片宽高是全局变量mWidth，mHeight
        Bitmap bitmap;
        if (aa == 1)
            bitmap = Bitmap.createBitmap(1000, 744, Bitmap.Config.ARGB_8888);
        else
            bitmap = Bitmap.createBitmap(660, 480, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable1.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable1.draw(canvas);
        return bitmap;
    }

    public static Bitmap circle(Bitmap bitmap,int color) {
        int angle = 50;  //角度
        int strokeWidth = 10; //边框宽度
        //从原bitmap中创建一个null的bitmap
        Bitmap temp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(temp); //放到画布中
        //使用BitmapShader方式来进行绘制
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, bitmap.getWidth(), bitmap.getHeight());
        //绘制出带圆角的位图
        canvas.drawRoundRect(rectF, angle, angle, paint);
        //创建绘制边框的画笔
        Paint paint1 = new Paint();
        paint1.setStyle(Paint.Style.STROKE);
        paint1.setStrokeWidth(strokeWidth);
        //这里要特别注意绘制边框矩形的参数，如果我们以(0,0,bitmap.getWidth(),bitmap.getHeight())来绘制边框
        //绘制完后会发现四个角的边框部分会突出一些，即边框看起来粗一些
        //这个原因是因为我们边框是5px宽度，当我们以0,0绘制时边框其实中心坐标应该是2/5,2/5处
        //所以会多出2/5的宽度，这个时候我们调整如下就ok了
        RectF rectF2 = new RectF(strokeWidth / 2, strokeWidth / 2, bitmap.getWidth() - strokeWidth / 2, bitmap.getHeight() - strokeWidth / 2);
        paint1.setColor(color);
        canvas.drawRoundRect(rectF2, angle, angle, paint1);
        return temp;
    }

    /**
     * 每1分钟更新一次数据
     */
    private static final int ONE_Miniute = 60 * 1000 * 10;
    private static final int PENDING_REQUEST = 0;
    public int id1[] = {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f, R.id.g, R.id.h, R.id.i, R.id.j, R.id.k, R.id.l, R.id.m, R.id.n, R.id.o, R.id.p, R.id.q, R.id.r, R.id.s, R.id.t, R.id.u, R.id.v, R.id.w, R.id.x, R.id.y};
    public int id2[] = {R.id.aa, R.id.ab, R.id.ac, R.id.ad, R.id.ae, R.id.af, R.id.ag, R.id.ah, R.id.ai, R.id.aj, R.id.ak, R.id.al, R.id.am, R.id.an, R.id.ao, R.id.ap, R.id.aq, R.id.ar, R.id.as, R.id.at, R.id.au, R.id.av, R.id.aw, R.id.ax, R.id.ay};
    public int id3[] = {R.id.a, R.id.b, R.id.f, R.id.g, R.id.k, R.id.l, R.id.p, R.id.q, R.id.u, R.id.v, R.id.w, R.id.x, R.id.y, R.id.r, R.id.s, R.id.t, R.id.m, R.id.n, R.id.o, R.id.h, R.id.i, R.id.j, R.id.c, R.id.d, R.id.e};
    public int id4[] = {R.id.aa, R.id.ab, R.id.af, R.id.ag, R.id.ak, R.id.al, R.id.ap, R.id.aq, R.id.au, R.id.av, R.id.aw, R.id.ax, R.id.ay, R.id.ar, R.id.as, R.id.at, R.id.am, R.id.an, R.id.ao, R.id.ah, R.id.ai, R.id.aj, R.id.ac, R.id.ad, R.id.ae};

    public AlarmService() {
    }

    public void nor() {
        //    Intent intentPrev = new Intent(this,up.class);
//        Bundle bundle = new Bundle();                           //创建Bundle对象
//        bundle.putString("something", "1");     //装入数据
//        intentPrev.putExtras(bundle);
        //   final PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this,PENDING_REQUEST,intentPrev,PENDING_REQUEST);
        //这里模拟后台操作
//        new Thread(new Runnable() {
        @SuppressLint("WrongConstant")
//            @Override
//            public void run() {
                int j = 0;
        String name1[] = new String[50];
        String loc[] = new String[50];
        int week[][] = new int[50][30];
        int we[] = new int[50];
        int day[] = new int[50];
        int jie[] = new int[50];
        try {
            FileInputStream fileInputStream = openFileInput("test.txt");
            FileChannel fi = fileInputStream.getChannel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            j = Integer.parseInt(bufferedReader.readLine());
            for (int i = 1; i < j; i++) {
                name1[i] = bufferedReader.readLine();
                loc[i] = bufferedReader.readLine();
                jie[i] = Integer.parseInt(bufferedReader.readLine());
                day[i] = Integer.parseInt(bufferedReader.readLine());
                we[i] = Integer.parseInt(bufferedReader.readLine());
                for (int p = 1; p <= we[i]; p++) {
                    week[i][p] = Integer.parseInt(bufferedReader.readLine());
                }
            }
//                    String str = null;
//                    while((str = bufferedReader.readLine()) != null)
//                    {
//                        Toast.makeText(AlarmService.this,str, Toast.LENGTH_SHORT).show();
//                    }
            fi.close();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("wj", "循环执行了，哈哈111." + System.currentTimeMillis());
        String channelId = "my channel"; //通知id
        String name = "weekday";
        String date = null;
        try {
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
            File file = new File(strFilePath, "date.txt");//在创建文件
            file.canRead();
            InputStream ff = null;
            ff = new FileInputStream(file);

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));
            date=bufferedReader.readLine();
            ff.close();
            bufferedReader.close();
//            ba = ba1;
//            sh = sh1;
//            fo = fo1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        String eTime = date;
        long nd = 1000 * 24 * 60 * 60 * 7;// 一天的毫秒数
        long diff = 0;
        long wee = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());
        String nowtime = simpleDateFormat.format(curDate);
        try {
            diff = simpleDateFormat.parse(nowtime).getTime() - simpleDateFormat.parse(eTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        wee = diff / nd + 1;// 计算周数
        //wee=2;
        for (int i = 1; i < 26; i++) {
            int fl = 0;
            int ji;
            ji = i / 5 + 1;
            if (i % 5 == 0) ji = ji - 1;
            int da;
            da = i % 5;
            if (da == 0) da = 5;
            outterLoop:
            for (int g = 1; g < j; g++) {

                if (day[g] - 1 == da && jie[g] == ji) {
                    for (int p = 1; p <= we[g]; p++) {
                        if (wee == week[g][p]) {
                            fl = 1;
                            str1[i] = name1[g] + loc[g];
                            break outterLoop;
                        }
                    }
                }
            }
            if (fl == 0) str1[i] = "";
        }
        fr();
        setc();
        NotificationManagerCompat manager = NotificationManagerCompat.from(AlarmService.this);
        RemoteViews notificationLayoutExpanded1 = new RemoteViews(getPackageName(), R.layout.test1);
        RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.matchp);
//notificationLayoutExpanded.setTextViewCompoundDrawables(R.id.af,R.drawable.close,R.drawable.close,R.drawable.close,R.drawable.close);
        //这里判定 如果是 8.0以上,会出现无效的情况。那么单独额外处理一下
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
            NotificationManager notificationManager =
                    (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }
//                final GradientDrawable drawable2 = new GradientDrawable();
//                drawable2.setShape(GradientDrawable.RECTANGLE);
//                drawable2.setGradientType(GradientDrawable.RECTANGLE);
//                drawable2.setCornerRadius(50);
//                drawable2.setColor(sh);
//                Drawable drawable=drawable2;
//                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
//
//        Bitmap bitmap1 = Bitmap.createBitmap(1000, 744, Bitmap.Config.ARGB_8888);
//        bitmap1.eraseColor(ba);
//        Bitmap bitmap = Bitmap.createBitmap(660, 480, Bitmap.Config.ARGB_8888);
//        bitmap.eraseColor(sh);
////                Bitmap bi=circle(bitmap);
        Bitmap bw = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
//
        Bitmap bx=getBitmapGradient(0);
        for (int o = 1; o < 26; o++) {
            notificationLayoutExpanded.setTextViewText(id2[o - 1], str1[o]);
            notificationLayoutExpanded.setTextColor(id2[o - 1], colorcan[0][0]);
            if (str1[o].equals("")) {
                notificationLayoutExpanded.setImageViewBitmap(id1[o - 1], bw);
            } else {
                //notificationLayoutExpanded.setImageViewResource(id1[o-1],R.drawable.radius_border);
                notificationLayoutExpanded.setImageViewBitmap(id1[o - 1],bx );
            }
        }
        if (fla == 1) {
            notificationLayoutExpanded.setImageViewBitmap(R.id.im, getBitmapGradient(1));
        } else if (fla == 2) {
            Uri imageUri;
            Bitmap bitmap = null;
//            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file";
//            imageUri = Uri.fromFile(new File(strFilePath, "lan.png"));
//            try {
//                bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
////            bbit = getAlplaBitmap(bbit, alp);
                        String path = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/lanbx.png";
            try {
                FileInputStream fis = new FileInputStream(path);
                bitmap = BitmapFactory.decodeStream(fis);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                /* try catch  可以解决OOM后出现的崩溃，然后采取相应的解决措施，如缩小图片，较少内存使用
                 * 但这不是解决OOM的根本方法，因为这个地方是压缩骆驼的最后一颗稻草，
                 * 解决方法是dump内存，找到内存异常原因。*/
            } catch (OutOfMemoryError error) {
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap = null;
                }
                System.gc();
            }
            notificationLayoutExpanded.setImageViewBitmap(R.id.im, bitmap);

        } else{
//            Drawable drawable = getResources().getDrawable(R.drawable.bg1);
//
//            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
//
//            Bitmap bitmap2 = bitmapDrawable.getBitmap();
//            notificationLayoutExpanded.setImageViewBitmap(R.id.im, bitmap2);
        }
        //为prev控件注册事件
        // notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn, prevPendingIntent);
        Intent addIntent = new Intent();
        addIntent.setAction("com.example.xujiafeng.notificationrefresh.add");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn, PendingIntent.getBroadcast(AlarmService.this, 10, addIntent, PendingIntent.FLAG_IMMUTABLE));
        Notification customNotification = new NotificationCompat.Builder(AlarmService.this,channelId)
//tzl2
                .setSmallIcon(R.drawable.ic_launcher_background)//小图标（显示在状态栏）
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setContent(notificationLayoutExpanded)
                .setCustomBigContentView(notificationLayoutExpanded)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
        customNotification.flags=Notification.FLAG_ONGOING_EVENT;
        manager.notify(1, customNotification);
//            }
//        }).start();
    }

    private class NotificationReceiver extends BroadcastReceiver {

        @SuppressLint("WrongConstant")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "com.example.xujiafeng.notificationrefresh.add":
                    System.out.println("888888888888888");
                    for (int i = 1; i < 26; i++) {
                        str2[i] = "";
                    }

                    Bitmap bw = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
                    int j = 0;
                    String name1[] = new String[50];
                    String loc[] = new String[50];
                    int week[][] = new int[50][30];
                    int we[] = new int[50];
                    int day[] = new int[50];
                    int jie[] = new int[50];
                    try {
                        FileInputStream fileInputStream = openFileInput("test.txt");
                        FileChannel fi1 = fileInputStream.getChannel();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                        j = Integer.parseInt(bufferedReader.readLine());
                        for (int i = 1; i < j; i++) {
                            name1[i] = bufferedReader.readLine();
                            loc[i] = bufferedReader.readLine();
                            jie[i] = Integer.parseInt(bufferedReader.readLine());
                            day[i] = Integer.parseInt(bufferedReader.readLine());
                            we[i] = Integer.parseInt(bufferedReader.readLine());
                            for (int p = 1; p <= we[i]; p++) {
                                week[i][p] = Integer.parseInt(bufferedReader.readLine());
                            }
                        }
//                    String str = null;
//                    while((str = bufferedReader.readLine()) != null)
//                    {
//                        Toast.makeText(AlarmService.this,str, Toast.LENGTH_SHORT).show();
//                    }
                        fi1.close();
                        bufferedReader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e("wj", "循环执行了，哈哈222." + System.currentTimeMillis());
                    String channelId = "my channel1"; //通知id
                    String name = "weekend";
                    String date = null;
                    try {
                        String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
                        File file = new File(strFilePath, "date.txt");//在创建文件
                        file.canRead();
                        InputStream ff = null;
                        ff = new FileInputStream(file);

                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));
                        date=bufferedReader.readLine();
                        ff.close();
                        bufferedReader.close();
//            ba = ba1;
//            sh = sh1;
//            fo = fo1;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String eTime = date;
                    long nd = 1000 * 24 * 60 * 60 * 7;// 一天的毫秒数
                    long diff = 0;
                    long wee = 0;
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date curDate = new Date(System.currentTimeMillis());
                    String nowtime = simpleDateFormat.format(curDate);
                    try {
                        diff = simpleDateFormat.parse(nowtime).getTime() - simpleDateFormat.parse(eTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    wee = diff / nd + 1;// 计算周数
                    //wee=2;
                    for (int i = 1; i < 11; i++) {
                        int fl = 0;
                        int ji;
                        ji = i / 2 + 1;
                        if (i % 2 == 0) ji = ji - 1;
                        int da;
                        da = i % 2;
                        outterLoop:
                        for (int g = 1; g < j; g++) {

                            if (day[g] == da && jie[g] == ji) {
                                for (int p = 1; p <= we[g]; p++) {
                                    if (wee == week[g][p]) {
                                        fl = 1;
                                        str2[i] = name1[g] + loc[g];
                                        break outterLoop;
                                    }
                                }
                            }
                        }
                        if (fl == 0) str2[i] = "";
                    }
                    fr();
                    setc();
                    NotificationManagerCompat manager = NotificationManagerCompat.from(AlarmService.this);
                    RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.matchpexit);
                    RemoteViews notificationLayoutExpanded1 = new RemoteViews(getPackageName(), R.layout.test1);

                    //这里判定 如果是 8.0以上,会出现无效的情况。那么单独额外处理一下
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        NotificationChannel notificationChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
                        NotificationManager notificationManager =
                                (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.createNotificationChannel(notificationChannel);
                    }
//                final GradientDrawable drawable2 = new GradientDrawable();
//                drawable2.setShape(GradientDrawable.RECTANGLE);
//                drawable2.setGradientType(GradientDrawable.RECTANGLE);
//                drawable2.setCornerRadius(50);
//                drawable2.setColor(sh);
//                Drawable drawable=drawable2;
//                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
//
//                    Bitmap bitmap1 = Bitmap.createBitmap(1000, 744, Bitmap.Config.ARGB_8888);
//                    bitmap1.eraseColor(ba);
//                    Bitmap bitmap = Bitmap.createBitmap(660, 480, Bitmap.Config.ARGB_8888);
//                    bitmap.eraseColor(sh);
//                    Bitmap bi = circle(bitmap,colorcan[3][0]);
                    Bitmap bx=getBitmapGradient(0);
                    Bitmap fw=getBitmapGradient(1);
                    for (int o = 1; o < 26; o++) {
                        notificationLayoutExpanded.setTextViewText(id4[o - 1], str2[o]);
                        notificationLayoutExpanded.setTextColor(id4[o - 1], colorcan[0][0]);
                        if (str2[o].equals("")) {
                            notificationLayoutExpanded.setImageViewBitmap(id3[o - 1], bw);
                        } else {
                            //notificationLayoutExpanded.setImageViewResource(id1[o-1],R.drawable.radius_border);
                            notificationLayoutExpanded.setImageViewBitmap(id3[o - 1], bx);
                        }
                    }
                    if (fla == 1) {
                        notificationLayoutExpanded.setImageViewBitmap(R.id.im, fw);
                    } else if (fla == 2) {
                        Uri imageUri;
                        Bitmap bbit = null;
                        String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file";
                        imageUri = Uri.fromFile(new File(strFilePath, "lanbx.png"));
                        try {
                            bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                            bbit = getAlplaBitmap(bbit, alp);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        notificationLayoutExpanded.setImageViewBitmap(R.id.im, bbit);

                    } else ;
                    //为prev控件注册事件
                    // notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn, prevPendingIntent);
                    Intent addIntent = new Intent();
                    addIntent.setAction("com.example.xujiafeng.notificationrefresh.x");
                    Intent today = new Intent();
                    today.setAction("com.example.xujiafeng.notificationrefresh.today");
                    notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn1, PendingIntent.getBroadcast(AlarmService.this, 10, addIntent, PendingIntent.FLAG_IMMUTABLE));
                    notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn2, PendingIntent.getBroadcast(AlarmService.this, 10, today, PendingIntent.FLAG_IMMUTABLE));
                    Intent twoIntent = new Intent();
                    twoIntent.setAction("com.example.xujiafeng.notificationrefresh.two");
                    notificationLayoutExpanded.setOnClickPendingIntent(R.id.btn3, PendingIntent.getBroadcast(AlarmService.this, 10, twoIntent, PendingIntent.FLAG_IMMUTABLE));
                    Notification customNotification = new NotificationCompat.Builder(AlarmService.this,channelId)
//tzl2
                            .setSmallIcon(R.drawable.ic_launcher_background)//小图标（显示在状态栏）
                            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                            .setContent(notificationLayoutExpanded)
                            .setCustomBigContentView(notificationLayoutExpanded)
                            .setPriority(NotificationCompat.PRIORITY_MIN)
                            .setOnlyAlertOnce(true)
                            .setOngoing(true)
                            .build();
                    customNotification.flags=Notification.FLAG_ONGOING_EVENT;
                    manager.notify(1, customNotification);

                    break;
                case "com.example.xujiafeng.notificationrefresh.x":
                    nor();
                    setState(0);
                    break;
                case "com.example.xujiafeng.notificationrefresh.today":
                    today();
                    setState(1);
                    break;
                case "com.example.xujiafeng.notificationrefresh.next":
                    nextday();
                    break;
                case "com.example.xujiafeng.notificationrefresh.two":
                    twoday();
                    setState(2);
                    break;
            }
        }
    }
//TODO
int[] twotoday={R.id.am12,R.id.am22,R.id.pm12,R.id.pm22,R.id.n2};

    private void twoday() {
        makestr(false);
        String channelId = "my channel"; //通知id
        String name = "twoday";
        NotificationManagerCompat manager = NotificationManagerCompat.from(AlarmService.this);
        RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.twoday);
//notificationLayoutExpanded.setTextViewCompoundDrawables(R.id.af,R.drawable.close,R.drawable.close,R.drawable.close,R.drawable.close);
        //这里判定 如果是 8.0以上,会出现无效的情况。那么单独额外处理一下
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
            NotificationManager notificationManager =
                    (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Calendar c = Calendar.getInstance();
        int weekt = c.get(Calendar.DAY_OF_WEEK);
        int js=0;
        for(int i:idtoday){
            notificationLayoutExpanded.setTextViewText(i, str1[js*7+weekt]);
            notificationLayoutExpanded.setTextColor(i, 0xff000000);

            js++;
        }
        js=0;
        c.add(Calendar.DATE, 1);
        weekt = c.get(Calendar.DAY_OF_WEEK);
        if(weekt==0)makestr(true);
        for(int i:twotoday){
            notificationLayoutExpanded.setTextViewText(i, str1[js*7+weekt]);
            notificationLayoutExpanded.setTextColor(i, 0xff000000);

            js++;
        }

        Intent dayIntent = new Intent();
        dayIntent.setAction("com.example.xujiafeng.notificationrefresh.today");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.today, PendingIntent.getBroadcast(AlarmService.this, 10, dayIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent weekIntent = new Intent();
        weekIntent.setAction("com.example.xujiafeng.notificationrefresh.x");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.week, PendingIntent.getBroadcast(AlarmService.this, 10, weekIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent twoIntent = new Intent();
        twoIntent.setAction("com.example.xujiafeng.notificationrefresh.next");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.next, PendingIntent.getBroadcast(AlarmService.this, 10, twoIntent, PendingIntent.FLAG_IMMUTABLE));
        Notification customNotification = new NotificationCompat.Builder(AlarmService.this,channelId)
//tzl2
                .setSmallIcon(R.drawable.ic_launcher_background)//小图标（显示在状态栏）
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setContent(notificationLayoutExpanded)
                .setCustomBigContentView(notificationLayoutExpanded)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
        customNotification.flags=Notification.FLAG_ONGOING_EVENT;
        manager.notify(1, customNotification);


    }

    int[] idtoday={R.id.am1,R.id.am2,R.id.pm1,R.id.pm2,R.id.n1};

    private void nextday() {
        makestr(false);
        String channelId = "my channel"; //通知id
        String name = "nextday";
        NotificationManagerCompat manager = NotificationManagerCompat.from(AlarmService.this);
        RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.nextday);
//notificationLayoutExpanded.setTextViewCompoundDrawables(R.id.af,R.drawable.close,R.drawable.close,R.drawable.close,R.drawable.close);
        //这里判定 如果是 8.0以上,会出现无效的情况。那么单独额外处理一下
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
            NotificationManager notificationManager =
                    (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 1);
        int weekt = c.get(Calendar.DAY_OF_WEEK);
        int js=0;
        if(weekt==0)makestr(true);
        for(int i:idtoday){
            notificationLayoutExpanded.setTextViewText(i, str1[js*7+weekt]);
            notificationLayoutExpanded.setTextColor(i, 0xff000000);

            js++;
        }



        Intent dayIntent = new Intent();
        dayIntent.setAction("com.example.xujiafeng.notificationrefresh.today");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.day, PendingIntent.getBroadcast(AlarmService.this, 10, dayIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent weekIntent = new Intent();
        weekIntent.setAction("com.example.xujiafeng.notificationrefresh.x");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.week, PendingIntent.getBroadcast(AlarmService.this, 10, weekIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent twoIntent = new Intent();
        twoIntent.setAction("com.example.xujiafeng.notificationrefresh.two");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.two, PendingIntent.getBroadcast(AlarmService.this, 10, twoIntent, PendingIntent.FLAG_IMMUTABLE));
        Notification customNotification = new NotificationCompat.Builder(AlarmService.this,channelId)
//tzl2
                .setSmallIcon(R.drawable.ic_launcher_background)//小图标（显示在状态栏）
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setContent(notificationLayoutExpanded)
                .setCustomBigContentView(notificationLayoutExpanded)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
        customNotification.flags=Notification.FLAG_ONGOING_EVENT;
        manager.notify(1, customNotification);



    }

    private void today() {
        makestr(false);
        String channelId = "my channel"; //通知id
        String name = "today";
        NotificationManagerCompat manager = NotificationManagerCompat.from(AlarmService.this);
        RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.today);
//notificationLayoutExpanded.setTextViewCompoundDrawables(R.id.af,R.drawable.close,R.drawable.close,R.drawable.close,R.drawable.close);
        //这里判定 如果是 8.0以上,会出现无效的情况。那么单独额外处理一下
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
            NotificationManager notificationManager =
                    (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Calendar c = Calendar.getInstance();
        int weekt = c.get(Calendar.DAY_OF_WEEK);
int js=0;
    for(int i:idtoday){
        notificationLayoutExpanded.setTextViewText(i, str1[js*7+weekt]);
        notificationLayoutExpanded.setTextColor(i, 0xff000000);
        js++;
    }



        Intent dayIntent = new Intent();
        dayIntent.setAction("com.example.xujiafeng.notificationrefresh.next");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.day, PendingIntent.getBroadcast(AlarmService.this, 10, dayIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent weekIntent = new Intent();
        weekIntent.setAction("com.example.xujiafeng.notificationrefresh.x");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.week, PendingIntent.getBroadcast(AlarmService.this, 10, weekIntent, PendingIntent.FLAG_IMMUTABLE));
        Intent twoIntent = new Intent();
        twoIntent.setAction("com.example.xujiafeng.notificationrefresh.two");
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.two, PendingIntent.getBroadcast(AlarmService.this, 10, twoIntent, PendingIntent.FLAG_IMMUTABLE));
        Notification customNotification = new NotificationCompat.Builder(AlarmService.this,channelId)
//tzl2
                .setSmallIcon(R.drawable.ic_launcher_background)//小图标（显示在状态栏）
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setContent(notificationLayoutExpanded)
                .setCustomBigContentView(notificationLayoutExpanded)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
        customNotification.flags=Notification.FLAG_ONGOING_EVENT;
        manager.notify(1, customNotification);



    }

    private void makestr(boolean next) {
        int j = 0;
        String name1[] = new String[50];
        String loc[] = new String[50];
        int week[][] = new int[50][30];
        int we[] = new int[50];
        int day[] = new int[50];
        int jie[] = new int[50];
        try {
            FileInputStream fileInputStream = openFileInput("test.txt");
            FileChannel fi = fileInputStream.getChannel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            j = Integer.parseInt(bufferedReader.readLine());
            for (int i = 1; i < j; i++) {
                name1[i] = bufferedReader.readLine();
                loc[i] = bufferedReader.readLine();
                jie[i] = Integer.parseInt(bufferedReader.readLine());
                day[i] = Integer.parseInt(bufferedReader.readLine());
                we[i] = Integer.parseInt(bufferedReader.readLine());
                for (int p = 1; p <= we[i]; p++) {
                    week[i][p] = Integer.parseInt(bufferedReader.readLine());
                }
            }
//                    String str = null;
//                    while((str = bufferedReader.readLine()) != null)
//                    {
//                        Toast.makeText(AlarmService.this,str, Toast.LENGTH_SHORT).show();
//                    }
            fi.close();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("wj", "循环执行了，哈哈111." + System.currentTimeMillis());
        String channelId = "my channel"; //通知id
        String name = "weekday";
        String date = null;
        try {
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
            File file = new File(strFilePath, "date.txt");//在创建文件
            file.canRead();
            InputStream ff = null;
            ff = new FileInputStream(file);

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));
            date=bufferedReader.readLine();
            ff.close();
            bufferedReader.close();
//            ba = ba1;
//            sh = sh1;
//            fo = fo1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        String eTime = date;
        long nd = 1000 * 24 * 60 * 60 * 7;// 一天的毫秒数
        long diff = 0;
        long wee = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());
        String nowtime = simpleDateFormat.format(curDate);
        try {
            diff = simpleDateFormat.parse(nowtime).getTime() - simpleDateFormat.parse(eTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        wee = diff / nd + 1;// 计算周数
        wee=next?(wee+1):wee;
        //wee=2;
//        for (int i = 1; i < 26; i++) {
//            int fl = 0;
//            int ji;
//            ji = i / 5 + 1;
//            if (i % 5 == 0) ji = ji - 1;
//            int da;
//            da = i % 5;
//            if (da == 0) da = 5;
//            outterLoop:
//            for (int g = 1; g < j; g++) {
//
//                if (day[g] - 1 == da && jie[g] == ji) {
//                    for (int p = 1; p <= we[g]; p++) {
//                        if (wee == week[g][p]) {
//                            fl = 1;
//                            str1[i] = name1[g] + loc[g];
//                            break outterLoop;
//                        }
//                    }
//                }
//            }
//            if (fl == 0) str1[i] = "";
//        }
//        for (int i = 1; i < 11; i++) {
//            int fl = 0;
//            int ji;
//            ji = i / 2 + 1;
//            if (i % 2 == 0) ji = ji - 1;
//            int da;
//            da = i % 2;
//            outterLoop:
//            for (int g = 1; g < j; g++) {
//
//                if (day[g] == da && jie[g] == ji) {
//                    for (int p = 1; p <= we[g]; p++) {
//                        if (wee == week[g][p]) {
//                            fl = 1;
//                            str2[i] = name1[g] + loc[g];
//                            break outterLoop;
//                        }
//                    }
//                }
//            }
//            if (fl == 0) str2[i] = "";
//        }
        for (int i = 1; i < 36; i++) {
            int fl = 0;
            int ji;
            ji = i / 7 + 1;
            if (i % 7 == 0) ji = ji - 1;
            int da;
            da = i % 7;
//            if (da == 0) da = 5;
            outterLoop:
            for (int g = 1; g < j; g++) {

                if (day[g] == da && jie[g] == ji) {
                    for (int p = 1; p <= we[g]; p++) {
                        if (wee == week[g][p]) {
                            fl = 1;
                            str1[i] = name1[g] + loc[g];
                            break outterLoop;
                        }
                    }
                }
            }
            if (fl == 0) str1[i] = "";
        }
    }

    public void uu() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.xujiafeng.notificationrefresh.x");
        filter.addAction("com.example.xujiafeng.notificationrefresh.add");
        filter.addAction("com.example.xujiafeng.notificationrefresh.today");
        filter.addAction("com.example.xujiafeng.notificationrefresh.next");
        filter.addAction("com.example.xujiafeng.notificationrefresh.two");
        NotificationReceiver mReceiver = new NotificationReceiver();
        registerReceiver(mReceiver, filter);
    }

    static int pp = 1;

    /**
     * 调用Service都会执行到该方法
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        File fileEx = this.getExternalFilesDir(null);
        String dir = fileEx.getAbsolutePath() + "/test_abc";
        if (!fileEx.exists()) { // 先根据路径创建文件夹
            fileEx.mkdirs();
        }
        //    Intent intentPrev = new Intent(this,up.class);
//        Bundle bundle = new Bundle();                           //创建Bundle对象
//        bundle.putString("something", "1");     //装入数据
//        intentPrev.putExtras(bundle);
        //   final PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this,PENDING_REQUEST,intentPrev,PENDING_REQUEST);
        //这里模拟后台操作
        if (pp == 1) {
            uu();
            pp++;
        }
        new Thread(new Runnable() {
            //            @SuppressLint("WrongConstant")
            @Override
            public void run() {
                switch (getState()){
                    case 0:
                        nor();
                        break;
                    case 1:
                        today();
                        break;
                    case 2:
                        twoday();
                        break;
                     default:
                        break;
                }
            }
        }).start();
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime = SystemClock.elapsedRealtime() + ONE_Miniute;//从开机到现在的毫秒书（手机睡眠(sleep)的时间也包括在内
        Intent i = new Intent(this, AlarmReceive.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(this, PENDING_REQUEST, i, PendingIntent.FLAG_IMMUTABLE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pIntent);
        return super.onStartCommand(intent, flags, startId);
    }

    private int getState() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return settings.getInt("state", 0);
    }
    private void setState(int state) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        //4.添加要保存的键值和真值
        editor.putInt("state", state);
        editor.commit();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}